package netbayWatchDog;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class WatchDog {

	public static String servletUrl = "";
	public static String TCDRecvDir = "";
	public static String JPMCRecvDir = "";
	public static String TCDRecvCmd = "";
	public static String JPMCRecvCmd = "";
	
	public static Integer cycleDelay = 60;

	public static void main(String[] arg) {

		WatchDogUtility.initialize();

		boolean working = true;
		while (working) {
			checkTCDDir();
			checkJPMCDir();
			try {
				Thread.sleep(cycleDelay*1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	private static void checkTCDDir() {

//		System.out.println(TCDRecvDir);

		File TCDfolder = new File(TCDRecvDir);

		if (!TCDfolder.exists()) {
			System.out.println("the path given isn't existed");
			return;
		}

		String[] fileList = TCDfolder.list();

		if (fileList.length > 0) {

			// need to looking for ctrl file before call
			for (int i = 0; i < fileList.length; ++i) {
				if (fileList[i].substring(fileList[i].length() - 5,
						fileList[i].length()).equalsIgnoreCase(".ctrl")) {
					System.out.println("found target file");
					CallServlet(TCDRecvCmd);
				}
			}
		}
	}

	private static void checkJPMCDir() {
		// File TCDfolder = new File(JPMCRecvDir);
		//
		// if (!TCDfolder.exists()) {
		// System.out.println("the path given isn't existed");
		// return;
		// }

		SFTPManager manager = new SFTPManager();

		if (manager.lookForNewfile()) {
			CallServlet(JPMCRecvCmd);
		}
	}

	private static void CallServlet(String cmd) {
		try {

			// initial connection
			String parameter = "?cmd=" + cmd;

//			System.out.println(servletUrl + parameter);
			HttpURLConnection servletCaller = (HttpURLConnection) new URL(
					servletUrl + parameter).openConnection();
			servletCaller.setRequestMethod("GET");

			servletCaller.connect();
			servletCaller.getContent();

		} catch (MalformedURLException e) {
			System.out.println("the url given isn't function");
			try {
				// sleep for 5 minute to wait until network is better
				Thread.sleep(cycleDelay*1000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} catch (IOException e) {
			System.out.println("network connection has a problem");
			try {
				// sleep for 5 minute to wait until network is better
				Thread.sleep(cycleDelay*1000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

}
